package com.mulanweb.api.module.controller.admin;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;

import java.util.Date;

/**
 * Created by Administrator on 2016/9/26.
 */
@ValidateFile
public class HotCommodityController extends BaseController {

    @ValidateForm
    public void saveOrDelete() {
        Integer typeId = getParaToInt("typeId");
        Long targetId = getParaToLong("targetId");
        Integer adminId = getSessionAttr("adminId");
        AdminUser adminUser = AdminUser.dao.findById(adminId);
        if (StrKit.notNull(adminUser) && adminUser.getDeleteTime() == null) {
            if (typeId == 23 || typeId == 24) {
                HotCommodity hotCommodity = HotCommodity.dao.findFirst("SELECT * FROM hot_commodity WHERE target_id=? AND type_id=?", targetId, typeId);
                if (hotCommodity != null) {
                    if (hotCommodity.delete()) {
                        returnSuccessJson();
                    } else {
                        returnFailureJson();
                    }
                } else {
                    hotCommodity = new HotCommodity();
                    hotCommodity.setAdminId(adminId);
                    hotCommodity.setTypeId(typeId);
                    hotCommodity.setTargetId(targetId);
                    hotCommodity.setCreateTime(new Date());
                    if (hotCommodity.save()) {
                        returnSuccessJson();
                    } else {
                        returnFailureJson();
                    }
                }
            } else {
                returnJson(0, "类型错误");
            }
        } else {
            returnJson(0, "管理员未登录,或不合法");
        }
    }

    @ValidateForm
    public void search(){
        SQLGenerateHelper helper = new SQLGenerateHelper("hot_commodity","create_time desc");
        helper.addEqualsCondition("type_id",getPara("typeId"));
        Page<HotCommodity> page = HotCommodity.dao.paginate(getPageNumber(),getPageSize(),helper.getSqlSelect(),helper.getSqlExceptSelect(),helper.getQueryParas());
        returnPageModelJson(page);
    }
}
